package com.ms.oschina.tagpager;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ms.oschina.R;
import com.ms.oschina.api.remote.OsChinaApi;
import com.ms.oschina.base.AppContext;
import com.ms.oschina.base.BaseAsyncTask;
import com.ms.oschina.base.BaseFragment;
import com.ms.oschina.base.BasePagerSlidingTabFragment;
import com.ms.oschina.base.LoadingPager.ResultCode;
import com.ms.oschina.bean.Constants;
import com.ms.oschina.bean.HttpResponse;
import com.ms.oschina.bean.MyInformation;
import com.ms.oschina.bean.User;
import com.ms.oschina.ui.activity.FavoriteActivity;
import com.ms.oschina.ui.activity.FollowActivity;
import com.ms.oschina.ui.activity.MessageActivity;
import com.ms.oschina.util.CloneUtils;
import com.ms.oschina.util.LocalBroadcastUtils;
import com.ms.oschina.util.PreferenceUtils;
import com.ms.oschina.util.UiUtils;
import com.ms.oschina.view.CircleImageView;
import com.squareup.picasso.Picasso;

public class MineFragment extends BaseFragment implements OnClickListener {

	private TextView tvMyLogin;
	private CircleImageView civMyUserAvatar;
	private ImageView ivQrCode;
	private LinearLayout tvMyScore;
	private TextView tvMyScoreNum;
	private LinearLayout tvMyFavorite;
	private TextView tvMyFavoriteNum;
	private LinearLayout tvMyFollowing;
	private TextView tvMyFollowingNum;
	private LinearLayout tvMyFollower;
	private TextView tvMyFollowerNum;

	private LinearLayout llMyMessage;
	private TextView tvMyMessageNum;
	private LinearLayout llMyBlog;
	private TextView tvMyBlogNum;
	private LinearLayout llMyNote;
	private TextView tvMyNote;
	private TextView tvMyNoteNum;
	private LinearLayout llMyTeam;
	private TextView tvMyTeamNum;
	private ImageView ivGender;

	private void findViews(View view) {
		tvMyLogin = (TextView) view.findViewById(R.id.tv_my_login);
		civMyUserAvatar = (CircleImageView) view
				.findViewById(R.id.civ_my_userAvatar);
		ivQrCode = (ImageView) view.findViewById(R.id.iv_qr_code);
		ivGender = (ImageView) view.findViewById(R.id.iv_my_gender);
		tvMyScore = (LinearLayout) view.findViewById(R.id.tv_my_score);
		tvMyScoreNum = (TextView) view.findViewById(R.id.tv_my_score_num);
		tvMyFavorite = (LinearLayout) view.findViewById(R.id.tv_my_favorite);
		tvMyFavoriteNum = (TextView) view.findViewById(R.id.tv_my_favorite_num);
		tvMyFollowing = (LinearLayout) view.findViewById(R.id.tv_my_following);
		tvMyFollowingNum = (TextView) view
				.findViewById(R.id.tv_my_following_num);
		tvMyFollower = (LinearLayout) view.findViewById(R.id.tv_my_follower);
		tvMyFollowerNum = (TextView) view.findViewById(R.id.tv_my_follower_num);

		llMyMessage = (LinearLayout) view.findViewById(R.id.ll_my_message);
		tvMyMessageNum = (TextView) view.findViewById(R.id.tv_my_message_num);
		llMyBlog = (LinearLayout) view.findViewById(R.id.ll_my_blog);
		tvMyBlogNum = (TextView) view.findViewById(R.id.tv_my_blog_num);
		llMyNote = (LinearLayout) view.findViewById(R.id.ll_my_note);
		tvMyNote = (TextView) view.findViewById(R.id.tv_my_note);
		tvMyNoteNum = (TextView) view.findViewById(R.id.tv_my_note_num);
		llMyTeam = (LinearLayout) view.findViewById(R.id.ll_my_team);
		tvMyTeamNum = (TextView) view.findViewById(R.id.tv_my_team_num);
	}

	@Override
	public int getLayoutId() {
		return R.layout.fragment_mine;
	}

	@Override
	public void initView(View view) {
		findViews(view);
	}

	public void initEvent() {
		civMyUserAvatar.setOnClickListener(this);
		tvMyLogin.setOnClickListener(this);

		tvMyScore.setOnClickListener(this);
		tvMyFavorite.setOnClickListener(this);
		tvMyFollowing.setOnClickListener(this);
		tvMyFollower.setOnClickListener(this);

		llMyMessage.setOnClickListener(this);
		llMyBlog.setOnClickListener(this);
		llMyNote.setOnClickListener(this);
		llMyTeam.setOnClickListener(this);
	}

	public void initData() { // 设置登陆点击事件
		MyInformation localInfo = getLocalUserInfo();
		updateUser(localInfo);

		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(Constants.ACTION_EXTERNAL_USERCHANGE);
		UserUpdateReceiver mReceiver = new UserUpdateReceiver();
		LocalBroadcastUtils.registerReceiver(intentFilter, mReceiver);

		// 刷新数据
		Intent intent = new Intent(Constants.ACTION_EXTERNAL_USERCHANGE);
		LocalBroadcastUtils.sendBroad(intent);

	}

	private MyInformation getLocalUserInfo() {
		try {
			FileInputStream openFileInput = UiUtils.getContext().openFileInput(
					"config.properties");
			byte[] buffer = new byte[1024 * 100];
			openFileInput.read(buffer);
			return (MyInformation) CloneUtils.byte2obj(buffer);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;

	}


	@Override
	public void onClick(View v) {
		Context context = UiUtils.getContext();
		boolean isLogin = AppContext.isLogin();
		if (!isLogin) {
			UiUtils.login();
			return;
		}
		switch (v.getId()) {
		case R.id.civ_my_userAvatar:
			break;
		case R.id.tv_my_login:
			break;
		case R.id.tv_my_score:
			break;
		case R.id.tv_my_favorite: {// 收藏
			Intent intent = new Intent(context, FavoriteActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(intent);
			break;
		}
		case R.id.tv_my_following: {// 关注
			Intent intent = new Intent(context, FollowActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(intent);
			break;
		}
		case R.id.tv_my_follower:
			break;

		case R.id.ll_my_message:
			Intent intent = new Intent(context, MessageActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(intent);
			break;
		case R.id.ll_my_blog:
			break;
		case R.id.ll_my_note:
			break;
		case R.id.ll_my_team:
			throw new NullPointerException();
//			break;

		}
	}

	private class UserUpdateReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {

			final int uid = PreferenceUtils.getPrefInt(UiUtils.getContext(),
					Constants.UID, -1);
			if (uid == -1) {// 用户没有登录
				return;
			}

			// 请求网络数据
			new BaseAsyncTask<MyInformation>() {
				@Override
				protected MyInformation exeCute() throws Exception {
					MyInformation info = OsChinaApi.loginUser(uid);
					// 持久化存储对象
					saveUser(info);
					return info;
				}

				@Override
				protected void onPostExe(HttpResponse<MyInformation> result) {
					updateUser(result.response);
				}
			}.execute();

			// 请求登录页； 返回uid ，发送广播 根据uid重新获取数据 显示登录、显示用户信息

			// 当前页发送刷新页面的广播 ，查看是否登录： 以登录，根据uid重新获取数据
		}

		protected void saveUser(MyInformation info) {
			if (info == null) {
				return;
			}
			// 写入到文件中
			try {
				byte[] obj2byte = CloneUtils.obj2byte(info);
				FileOutputStream openFileOutput = UiUtils.getContext()
						.openFileOutput("config.properties",
								Context.MODE_PRIVATE);
				openFileOutput.write(obj2byte);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private void updateUser(MyInformation info) {
		if (info == null) {// 网络连接失败
			return;
		}

		// 查看用户是否登录
		boolean isLogin = PreferenceUtils.getPrefBoolean(UiUtils.getContext(),
				Constants.IS_LOGIN, false);

		if (isLogin) {
			updateUi(info);
		} else {
			ivGender.setVisibility(View.GONE);
			ivQrCode.setVisibility(View.GONE);
		}
	}

	private void updateUi(MyInformation info) {

		ivQrCode.setVisibility(View.VISIBLE);
		ivGender.setVisibility(View.VISIBLE);

		User user = info.getUser();
		if (user == null) {
			return;
		}
		int favoriteCount = user.getFavoritecount();// 收藏
		String gender = user.getGender();
		int fans = user.getFans();
		int followers = user.getFollowers();// 关注
		String name = user.getName();
		String portrait = user.getPortrait();

		tvMyLogin.setText(name);

		tvMyFavoriteNum.setText("" + favoriteCount);
		tvMyFollowingNum.setText("" + followers);
		if (!TextUtils.isEmpty(portrait)) {
			Picasso.with(UiUtils.getContext()).load(portrait)
					.placeholder(R.drawable.widget_dface).into(civMyUserAvatar);
		}
	}

}
